from django.shortcuts import render

# Create your views here.
import json
import re
from django import http
from django.views import View
from django.contrib.auth import login
from django_redis import get_redis_connection
from shicifang.settings import logger
from django.contrib.auth import logout

from apps.users.models import User
from django.contrib.auth import authenticate, login

# 注册
from shicifang.utils.views import LoginRequiredJSONMixin


class RegisterView(View):

    def post(self, request):
        # 1.接受参数　json
        json_dict = json.loads(request.body.decode())

        # 2.解析参数
        username = json_dict.get('username')
        mobile = json_dict.get('mobile')
        sms_code = json_dict.get('sms_code')
        password = json_dict.get('password')
        # allow = json_dict.get('allow')

        # 3.校验参数
        if not all([username, mobile, sms_code, password]):
            return http.JsonResponse({'code': 400, 'errmsg': '参数不齐!'})

        # 3.1 判断 用户名的正则 用户名是否重复
        if not re.match('^[a-zA-Z0-9_-]{5,20}$', username):
            return http.JsonResponse({'code': 400, 'errmsg': '用户名格式有误!'})
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})
        if count == 1:
            return http.JsonResponse({'code': 400, 'errmsg': '用户名已存在'})
        # 3.2 判断  mobile的正则
        if not re.match('^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': '手机号格式有误!'})
        # 3.3 密码的正则
        if not re.match('^[a-zA-Z0-9_-]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': '密码格式有误!'})
        # 3.5 是否勾选同意
        # if allow != True:
        #     return http.JsonResponse({'code': 400, 'errmsg': '勾选同意!'})

        # 3.6.1 获取后台验证码
        # sms_code_server = '111111'
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        # 校验
        if not sms_code_server:
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码过期了'})
        if sms_code != sms_code_server.decode():
        # if sms_code != sms_code_server:
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码有误!'})

        # 4.user增加
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '注册失败!'})
        # 保持登录状态
        login(request, user)

        # 5.返回json
        response = http.JsonResponse({'code': 0, 'errmsg': '注册成功!'})
        response.set_cookie('username', user.username, max_age=24 * 14 * 3600)
        return response

# 　登录
class LoginView(View):

    def post(self, request):
        # 1.接收参数
        json_dict = json.loads(request.body.decode())
        username = json_dict.get('username')
        password = json_dict.get('password')
        remembered = json_dict.get('remembered')

        # 2.校验参数
        if not all([username, password]):
            return http.JsonResponse({'code': 400, 'errmsg': '参数不齐!'})

        # 1.多账号登录
        if re.match('^1[3-9]\d{9}$', username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        # 3.对比数据库
        user = authenticate(request, username=username, password=password)
        if user is None:
            return http.JsonResponse({'code': 400, 'errmsg': '用户名或密码错误!'})
        # 保持登录
        login(request, user)
        # 是否记住
        if remembered != True:
            request.session.set_expiry(0)
        else:
            # 记住登录  2周就过期
            request.session.set_expiry(None)

        response = http.JsonResponse({'code': 0, 'errmsg': '登录成功'})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        return response

# 退出
class LogoutView(View):
    def delete(self, request):

        logout(request)

        response = http.JsonResponse({'code': 0, 'errmsg': '退出成功!'})
        response.delete_cookie('username')

        return response

# 用户中心
class UserInfoView(LoginRequiredJSONMixin, View):
    def get(self, request):
        return http.JsonResponse({
            'code': 0,
            'errmsg': '个人中心',
            "info_data": {
                "username": request.user.username,
                "mobile": request.user.mobile,
            }
        })




